import React, { useEffect, useState, useRef, useMemo } from 'react'
import "../css/index.scss"
import { CartO } from '@react-vant/icons';
import { Button, Space, Stepper } from 'antd-mobile'
import { AntOutline } from 'antd-mobile-icons'
import axios from 'axios'
import { useNavigate } from 'react-router-dom'
import stores from "../Redux/store"

export default function ShoppMain() {
    let history = useNavigate()
    let [messlis, setmesslis] = useState([])

    let [shopplis, setshopplis] = useState([])

    let getMess = async () => {
        let val = await axios.get("http://127.0.0.1:3000/xuweixin/carshow")
        let admin = JSON.parse(localStorage.getItem("adminmess"))
        setmesslis(val.data.datas ? val.data.datas.filter(item => item.uid == admin._id) : [])
    }

    let getGodds = async () => {
        let val = await axios.get("http://127.0.0.1:3000/xuweixin/messshow")

        setshopplis(val.data.datas.sort((a, b) => { return b.salesnum - a.salesnum }).slice(0, 9))
    }

    useEffect(() => {
        getMess()
        getGodds()
    }, [])

    let time = null
    let time2 = null
    return (
        <div>
            <div style={{ width: "100vw", height: "100vh", background: "#f7f7f7" }}>
                <div style={{ height: "47px", background: "white", textAlign: "center", lineHeight: "47px", position: "sticky", top: "0px", zIndex: "100" }}>
                    <b>购物车</b>
                </div>
                {/* 信息区域 */}
                <div style={{ height: "calc(100vh - 70px)" }}>
                    {
                        messlis.length == 0 ?
                            <div style={{ height: "325px", background: "white", marginTop: "20px", border: "1px solid white" }}>
                                <p style={{ textAlign: "center", marginTop: "47px" }}>
                                    <img src="./xuimgs/kong.jpg" style={{ width: "238px" }}></img>
                                </p>
                                <p style={{ textAlign: "center", marginTop: "8px" }}>
                                    <Button
                                        className='goshoppbut'
                                        style={{ animationName: messlis.length != 0 ? "" : "butaction", animationDuration: "1s", borderRadius: "50px", width: "115px", height: "42px" }} color='success'>去逛逛</Button>
                                </p>
                            </div>
                            :
                            <div style={{
                                height: "325px", overflow: "auto", background: "white", marginTop: "20px", border: "1px solid white"
                            }}>
                                {
                                    messlis.map(item => (
                                        <div
                                            style={{
                                                display: 'flex',
                                                justifyContent: 'space-between',
                                            }}
                                            key={item._id}>
                                            <p
                                                style={{ marginTop: "43px", marginLeft: "20px", marginRight: "-57px" }}
                                            ><input type="checkbox"
                                                checked={item.flag}

                                                onChange={(e) => {
                                                    clearTimeout(time2)
                                                    time2 = setTimeout(async () => {
                                                        let val = await axios.post("http://127.0.0.1:3000/xuweixin/updateflag", {
                                                            _id: item._id, uid:
                                                                JSON.parse(localStorage.getItem("adminmess"))._id
                                                        })
                                                        getMess()
                                                    }, 10)
                                                }}
                                                /></p>
                                            <p style={{ marginRight: "117px", marginRight: "-61px" }}>
                                                <img src={item.img} style={{ width: "100px", height: "100px" }}></img>
                                            </p>
                                            <p style={{ display: "flex", flexDirection: "column", justifyContent: 'space-around' }}>
                                                <span
                                                    style={{ marginTop: "16px", marginBottom: "-10px" }}
                                                >{item.name}</span>
                                                <span>{item.mess}</span>
                                                <span style={{ color: "#fe4545" }}>￥{item.price}</span>
                                            </p>
                                            <div style={{ marginTop: "71px", marginRight: "20px" }}>
                                                <Stepper
                                                    defaultValue={item.buynum}
                                                    onChange={async value => {
                                                        if (value > 0) {
                                                            clearTimeout(time)
                                                            time = setTimeout(async () => {
                                                                let val = await axios.post("http://127.0.0.1:3000/xuweixin/changenum", { _id: item._id, num: value })
                                                                getMess()
                                                                getGodds()
                                                            }, 500)

                                                        } else {
                                                            let vals = await axios.post("http://127.0.0.1:3000/xuweixin/remove", { _id: item._id })
                                                            getMess()
                                                            getGodds()
                                                        }
                                                    }}
                                                />
                                            </div>
                                        </div>
                                    ))
                                }
                            </div>
                    }

                    {/* 热销商品 */}
                    <div style={{ height: "50px", textAlign: "center", lineHeight: "50px", background: "#f7f7f7" }}>
                        <b>--热销商品--</b>
                    </div>

                    {/* 热销商品信息 */}
                    <div className="bigdiv" style={{ borderRadius: "16px", background: "#f7f7f7", display: "flex", justifyContent: "", flexWrap: "wrap", textAlign: "center" }}>
                        {
                            shopplis.map(item => (
                                <div key={item._id} style={{ flex: "30%", textAlign: "center", background: "white", height: "257px", marginBottom: "20px" }}>
                                    <p><img src={item.img} style={{ width: "100px", height: "180px" }}></img></p>
                                    <p>
                                        <span>{item.name}</span>
                                        <span>{item.specTitle}</span>
                                    </p>
                                    <p>
                                        <span>{item.desc.length > 8 ? item.desc.substr(0, 8) + "..." : item.desc}</span>
                                    </p>
                                    <p style={{ display: "flex", justifyContent: 'space-between', marginTop: "10px" }}>
                                        <span style={{ color: "#fe4545", marginLeft: "10PX" }}>￥{item.price}</span>
                                        <span style={{ fontSize: "25px", marginRight: "13px" }}><CartO
                                            onClick={async () => {
                                                let adminmess = JSON.parse(localStorage.getItem("adminmess"))
                                                let vals = await axios.post("http://127.0.0.1:3000/xuweixin/addcar", {
                                                    _id: item._id,
                                                    name: item.name,
                                                    price: item.price,
                                                    buynum: 1,
                                                    img: item.img,
                                                    flag: false,
                                                    mess: item.specTitle,
                                                    uid: adminmess._id,
                                                    shoppid: item._id
                                                })
                                                if (vals.data.code == 200) {
                                                    getMess()
                                                    getGodds()
                                                }
                                            }}
                                        ></CartO></span>
                                    </p>
                                </div>
                            ))
                        }
                    </div>
                </div>
            </div>

            {/* 结算部分 */}

            {
                messlis.length != 0 &&
                <div style={{
                    display: "flex",
                    justifyContent: 'space-between',
                    width: "100%",
                    height: "60px", background: "white", borderTop: "1px solid #f2f2f2", borderBottom: "1px solid #f2f2f2", position: "fixed", bottom: "52px",

                }}>

                    <p style={{ lineHeight: "60px", marginLeft: "10px" }}>
                        <input type="checkbox"
                            checked={messlis.every(flag => { return flag.flag == true })}
                            onChange={async (e) => {
                                // 全选
                                let newmesslis = [...messlis]
                                newmesslis.forEach(item => {
                                    item.flag = e.target.checked
                                })
                                setmesslis(newmesslis)
                                let val = await axios.post("http://127.0.0.1:3000/xuweixin/changeall", { flag: e.target.checked, uid: JSON.parse(localStorage.getItem("adminmess"))._id, msslis: messlis.map(item => { return item._id }) })
                            }}
                        ></input>
                        <span style={{ marginLeft: "10px" }}>全选</span>
                    </p>
                    <p style={{ display: 'flex', flexDirection: "column", justifyContent: "space-evenly", marginRight: "69px" }}>
                        <span style={{ color: "#fe4545", fontSize: "14px", marginBottom: "-10px" }}>总计：{messlis.filter(item => item.flag == true).reduce((sum, item) => { return sum += item.price * item.buynum }, 0).toFixed(2)}</span>
                        <span style={{ fontSize: "12px" }}>商品金额￥0.00，优惠￥0.00</span>
                    </p>

                    <p style={{ lineHeight: "60px", marginRight: "10px" }}>
                        <Button
                            onClick={() => {
                                history(`/submitbuy`)
                                stores.dispatch({
                                    type: "add",
                                    val: messlis.filter(item => item.flag == true && item.uid == JSON.parse(localStorage.getItem("adminmess"))._id)
                                })

                            }}
                            disabled={messlis.filter(item => item.flag == true).length == 0}
                            style={{ background: messlis.filter(item => item.flag == true).length == 0 ? "gray" : "#fe4545", borderRadius: "30px", color: "white" }}>去结算</Button>
                    </p>
                </div>
            }
            <div style={{ height: "50px", background: "yellowgreen", position: "fixed", bottom: "0px", width: "100%" }}>

            </div>
        </div>
    )
}
